#pragma once
#include<iostream>
#include "Thread.hpp"
#include<pthread.h>
#include<string>
#include<vector>
#include<queue>
#include"LockGuard.hpp"
#include<unistd.h>

using namespace std;

const static int N = 5;

template <class T>
class ThreadPool
{
public:
    ThreadPool(int num = N):_num(num)
    {
        pthread_mutex_init(&_lock,nullptr);
        pthread_cond_init(&_cond,nullptr);
    }

    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    bool isempty()
    {
        return _tasks.empty();
    }

    pthread_mutex_t *getlock()
    {
        return &_lock;
    }

    void threadWait()
    {
        pthread_cond_wait(&_cond,&_lock);
    }
     void threadWakeup()
    {
        pthread_cond_signal(&_cond);
    }


    static void threadRoutine(void* args)
    {
        ThreadPool<T> *tp = static_cast< ThreadPool<T> *>(args);
        while(1)
        {
            //检测有没有任务，有则处理，无则等待，都要加锁
            T t;
            {
                //LockGuard Lockguard(tp->_lock);
                LockGuard Lockguard(tp->getlock());
                while(tp->isempty())
                {
                    tp->threadWait();
                }
                 
                t = tp->popTask();//从公共区域拿到私有区域
            }
            t();
            std::cout << "thread handler done, result: " << t.formatRes() << std::endl;

        }
    }

    void init()
    {
        for(int i = 0;i<_num;i++)
        {
            _threads.push_back(Thread(i,threadRoutine,this));
        }
    }
    void start()
    {
        for(auto &a : _threads)
        {
            a.run();
        }
    }
    void check()
    {
        for(auto &a : _threads)
        {
            LockGuard lockguard(&_lock);
            cout<<a.threadname()<<" running "<<endl; 
            //sleep(1);
        }
    }

    void pushTask(const T &t)
    {
        LockGuard lockguard(&_lock);
        _tasks.push(t);
        threadWakeup();

    }

    

    ~ThreadPool()
    {
        for(auto &a : _threads)
        {
            a.join();
            //pthread_join(a._tid,nullptr);
        }
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }

private:
    vector<Thread> _threads;
    int _num;

    queue<T> _tasks;//使用slt自动扩容的特性

    pthread_mutex_t _lock;
    pthread_cond_t _cond;

};